<?php 
class  AdminaccountsController extends Controller{
	  
	 public function accessRules()
		 {
			return array(
			 
				array(
					'allow',  // allow all users to access 'index' and 'view' actions.
					'expression'=>'$user->rights == 3',
				),
				array(
					'deny',  // deny all users
					'users'=>array('*'),
					'message'=>'You do not have access to this page ! ! ',
				),
				
			);
		 } 
      public function actionIndex(){
		   $this->breadcrumbs=array(
               '用户管理'=>array('index'),
               '所有学生',
             );
		  $classRooms  = Classroom::model()->findAll();
		  $major = Major::model()->findAll();
		  $ci  = new CDbCriteria();
		  $ci->addCondition('rights = 1');
		 if(!empty($_GET) && (count($_GET) == 4)){
		  foreach($_GET as $key => $value){
			  if($value == '')
				  continue;
			  if($key == 'stuNumber'){
				  $ci->params[':s'] = $_GET['stuNumber'];
				  $ci->addCondition('username = :s');		  
			  }else{
			   $p = ':'.substr($key,0,1);	  
			   $ci->params[$p] = $value;
               $ci->addCondition('stuinfo.'.$key.' = '.$p);  
			  }
			  
		  }
		  
		 }
		  $ci->with = array('stuinfo');
		  $total = User::model()->count($ci);
		  //var_dump($ci->condition);var_dump($ci->params);die();
		  $pages =  new CPagination($total);
		  $pages->pageSize = 60;
		  $pages->applyLimit($ci);
		  $users = User::model()->findAll($ci);
		  $this->render('index',array('major'=>$major,'total'=>$total,'users'=>$users,'pages'=>$pages,'classRooms'=>$classRooms));
		  
	  }
	  
	 public function actionAddteachers(){
		 $this->breadcrumbs=array(
               '用户管理'=>array('index'),
               '添加教师用户',
             );
          $request  = Yii::app()->request;
		  if($request->requestType == 'POST'){
			  
			  $this->dealAddTeachers();
			  
		  }
		 $teachers = User::model()->findAll('rights = 2');
		 $this->render('addteachers',array('teachers'=>$teachers));
	 }
	protected function dealAddTeachers(){
		 $request  = Yii::app()->request;
		 
		 $u = new User;
		 $u->username = $request->getParam('username');
		 $u->password = $request->getParam('password');
		 $u->rights   = 2;
		 $u->isNew    = 0;
		 
		 if($u->save()){
			 Yii::app()->user->setFlash('update','添加成功');
		 }else{
			 Yii::app()->user->setFlash('update','添加失败');
		 }
		 $this->redirect(array('adminaccounts/addteachers'));
	 
	}
	public  function actionDeleteteacher(){
		 $request  = Yii::app()->request;
		 
		 if($request->isAjaxRequest){
			$uId = $request->getParam('uId');
           	$user = User::model()->findByPk($uId);
            if($user){
				if($user->delete()){
					echo json_encode(array('msg'=>'删除成功!','code'=>200));
				}else{
					echo json_encode(array('msg'=>'删除失败!','code'=>501));
				}
			}else{
			     echo json_encode(array('msg'=>'未发现用户','code'=>404));   	
				
			}	
			 
		 }else{
			  $this->redirect(array('adminaccounts/addteachers'));
			 
		 }
		
	}
	public function actionAdddata(){
		$this->breadcrumbs=array(
               '用户管理'=>array('index'),
               '添加学生用户',
             );
		if(Yii::app()->request->isPostRequest){
			
			if($_FILES['excel']['type'] !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
				Yii::app()->user->setFlash('adddata','请选择正确的文件');
			}else{
			    $this->importStu($_FILES['excel']);
			}
			
			
		}
		 
		 $this->render('adddata');
	}
	//@param
	// $file -----> $_FILES['name']
	private function importStu($file){
	  $successNum = 0;
	  $fileName = date('Y-m-d-H').'stuimports.xlsx';
	  
	  if(move_uploaded_file($file['tmp_name'],'./images/uploaded_excel/'.$fileName)){
		 // 禁止使用 Yii 自带的 加载 函数，因为这个加载函数与 phpExcel 自带的函数冲突，使用 include 来导入 IoFactory
		 Yii::$enableIncludePath = false;
		 Yii::import('application.extensions.phpExcel.PHPExcel',1);
         
         $type =  PHPExcel_IOFactory::identify('images/uploaded_excel/'.$fileName);
		 if( $type !== 'Excel5' && $type !== 'Excel2007' ){
			  Yii::app()->user->setFlash('add','请选择正确的文件');
			  return;
		 }
		 $reader = PHPExcel_IOFactory::createReader($type);
		 $reader->setReadDataOnly();
		 $reader->setLoadSheetsOnly('Sheet1');
		 $objPHPExcel =$reader->load('images/uploaded_excel/'.$fileName);
         $WorkSheet = $objPHPExcel->getActiveSheet();
		
		 $maxRow = $WorkSheet->getHighestRow();
		 
		 for($i = 2;$i <= $maxRow;$i++){
			 $u = new User;
			 $username = $WorkSheet->getCellByColumnAndRow(0,$i)->getValue();
			 $password = substr($username,-6);
			 $u->username = $username;
			 $u->password = $password;
			 $u->rights = 1;
			 $u->isNew = 1;
			 if($u->save()){
				$successNum++;
			}else{
				 $this->logAr($u);
		     }
			 
		 }		 
		  
	  }else{
		  Yii::app()->user->setFlash('adddata','文件上传失败');
		  
	  }
	  $maxRow-=1;
	  $chazhi = $maxRow - $successNum;
	  Yii::app()->user->setFlash('adddata','共有数据：'.$maxRow.'条<br>导入成功：'.$successNum.'<br>导入失败：'.$chazhi.'<br>错误原因：可能是系统中已经有这个用户或者文件内容不符合规定，请检查，谢谢');
		
	}
	public function actionAddperformance(){
		 $this->breadcrumbs=array(
               '用户管理'=>array('index'),
               '添加学生成绩',
             );
		 $request = Yii::app()->request;
		 if($request->requestType == 'POST'){
			
			if($_FILES['up']['name'] == '' && $_FILES['down']['name'] == ''){
			   Yii::app()->user->setFlash('add','请选择文件！！');
			   $this->redirect(array('adminaccounts/addperformance'));
			}
			 if($request->getParam('term') == '1'||$request->getParam('term') == '2'||$request->getParam('term') == '3'||$request->getParam('term') == '4'){
				 
				 $term  = (int)$request->getParam('term');
				 
				 if(CUploadedFile::getInstanceByName('up')){
					 $file  = CUploadedFile::getInstanceByName('up');
					 
					 if($file->type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
					 $this->importStuPerformance($file,2*$term - 1);
					 }else{
						 Yii::app()->user->setFlash('add','请选择 excel 文件上传');
						 $this->redirect(array('adminaccounts/addperformance'));
					 }
					 
				 }else{
					  $file  = CUploadedFile::getInstanceByName('down');
					
					 if($file->type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
						$this->importStuPerformance($file, $term*2);
					  }else{
						 Yii::app()->user->setFlash('add','请选择 excel 文件上传');
						  $this->redirect(array('adminaccounts/addperformance'));
					  }
				 }
				 
			 }
			
			
		 }
		   
	    
		 $this->render('addperformance');
	}
	private function importStuPerformance($file,$term){
		$term = 'term_'.$term;
		$realFile = 'images/uploaded_excel/'.date('Y-m-d-H-i').'stuPerformance.xlsx';
        $successNum = 0;
		$maxRow = 0;
		$noUser = 0; 
		if(move_uploaded_file($file->tempName,'./'.$realFile)){
		 // 禁止使用 Yii 自带的 加载 函数，因为这个加载函数与 phpExcel 自带的函数冲突，使用 include 来导入 IoFactory
		 Yii::$enableIncludePath = false;
		 Yii::import('application.extensions.phpExcel.PHPExcel',1);
         
         $type =  PHPExcel_IOFactory::identify($realFile);
		 if($type !== 'Excel5' && $type !== 'Excel2007'){
			 Yii::app()->user->setFlash('add','请选择正确的文件');
			 return;
		 }
		 $reader = PHPExcel_IOFactory::createReader($type);
		 $reader->setReadDataOnly();
		 $reader->setLoadSheetsOnly('Sheet1');
		 $objPHPExcel =$reader->load($realFile);
         $WorkSheet = $objPHPExcel->getActiveSheet();
		
		 $maxRow = $WorkSheet->getHighestRow();
		 
		 for($i = 2;$i <= $maxRow;$i++){
			 
			 $stuNum = $WorkSheet->getCellByColumnAndRow(0,$i)->getValue();
			 $per = $WorkSheet->getCellByColumnAndRow(1,$i)->getValue();
			 
			 
			 $stuPer = Stuperformance::model()->with(array('u'))->find('u.username = :u',array(':u'=>$stuNum));
			 if(!$stuPer){
				 $stuPer = new Stuperformance;
				 $user = User::model()->find('username = :u',array(':u'=>$stuNum));
				 if(!$user){
					$noUser++;
					continue;
				 }	
			         $stuPer->uId = $user->uId;
			 }
			 $stuPer->$term = $per;
			 if($stuPer->save()){
				 $successNum++;
				 
			 }else{
				 $this->logAr($stuPer);
			 }
			 
		 }		 
		  
			
		}else{
			Yii::app()->user->setFalsh('add','文件上传失败！');
			
		}		
	  $maxRow-=2;
	  $chazhi = $maxRow - $successNum;
	  Yii::app()->user->setFlash('add','成绩导入：共有数据：'.$maxRow.'条<br>导入成功：'.$successNum.'<br>导入失败：'.$chazhi.'<br>'.'没有在系统找到与该学号相符的同学而导致的成绩导入失败的学生数：'.$noUser);
	}
	public function actionReset(){
		
		if(Yii::app()->request->isAjaxRequest){
			$uId = $_POST['uId'];
			$user = User::model()->findByPk($uId);
			if($user){
				$user->password = substr($user->username,-6);
				$user->isNew = 1;
				
				if($user->save()){
					echo '学号为：'.$user->username.' 的学生密码重置成功，请使用学号后六位登陆，然后尽快修改密码.';
					
				}else{
					
					echo '重置失败';
				}
				
			}else{
				echo '没有找到用户';
				
			}
			
			
		}else{
			echo 'invalid access';
			
		}
		
	}
	
	public function actionDelete(){
		
		if(Yii::app()->request->isAjaxRequest){
			$uId = $_POST['uId'];
			$user = User::model()->findByPk($uId);
			if($user){
				$username = $user->username;
				if($user->delete()){
					echo json_encode(array('msg'=>'学号为：'.$username.' 的学生删除成功!','code'=>200));
					
				}else{
					
				  echo json_encode(array('msg'=>'删除失败','code'=>401));
				}
				
			}else{
				echo json_encode(array('msg'=>'没有找到用户','code'=>404));
				
			}
			
			
		}else{
			echo 'invalid access';
			
		}
		
	}
	
	public  function actionDownloadtemplete(){
		$request = Yii::app()->request;
		
		$file = $request->getParam('type');
		$fileName =  '';
		if($file == 'performance'){
			
			$fileName = '';
			
		}else{
			
			$fileName = '';
		}
		
		$fileinfo = pathinfo($filename);
		header('Content-type: application/x-'.$fileinfo['extension']);
		header('Content-Disposition: attachment; filename='.$fileinfo['basename']);
		header('Content-Length: '.filesize($filename));
		readfile($thefile);
		exit();
		
	}
}